package com.anxin.registerManagement.service.datav;

import com.anxin.registerManagement.bean.dto.datav.RoleDistributionDto;
import com.anxin.registerManagement.bean.persist.Role;
import com.anxin.registerManagement.bean.persist.code.CodeRoleName;
import com.anxin.registerManagement.bean.persist.relation.UserRoleRelation;
import com.anxin.registerManagement.mapper.RoleMapper;
import com.anxin.registerManagement.mapper.code.CodeRoleNameMapper;
import com.anxin.registerManagement.mapper.relation.UserRoleRelationMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author anxin
 * @date 2022/4/3 20:58
 */
@Service
public class DatavService {

    @Autowired
    CodeRoleNameMapper codeRoleNameMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleRelationMapper userRoleRelationMapper;

    public List<RoleDistributionDto> getRoleDistribution() {
        List<RoleDistributionDto> roleDistributionDtoList = new ArrayList<>();
        // 获取所有的角色名称
        List<CodeRoleName> codeRoleNameList = codeRoleNameMapper.selectList(null);
        for (CodeRoleName codeRoleName : codeRoleNameList) {
            RoleDistributionDto roleDistributionDto = new RoleDistributionDto();
            // 通过角色代码表的名称，去查对应角色表的id
            Role role = roleMapper.selectOne(new LambdaQueryWrapper<Role>()
                    .eq(Role::getRoleName, codeRoleName.getValue()));
            // 如果角色存在，则通过角色id获取该角色的人数
            if (!ObjectUtils.isEmpty(role)) {
                Long roleAccount = userRoleRelationMapper.selectCount(
                        new LambdaQueryWrapper<UserRoleRelation>()
                                .eq(UserRoleRelation::getRoleId, role.getId()));
                if (roleAccount != 0) {
                    // 如果有数量就设置，没有数量就不设置
                    roleDistributionDto.setValue(roleAccount);
                    roleDistributionDto.setName(codeRoleName.getValue());
                    roleDistributionDtoList.add(roleDistributionDto);
                }
            }
        }
        return roleDistributionDtoList;
    }
}
